class_name SteeringBehaviorHelper_GetTarget
extends SteeringBehaviorHelper

#region 属性
@export var radius:float = 30
@export var target_type:GameEnum.TargetDetectorTargetType
var ray_cast_2d:RayCast2D
var targets:Array[Node2D]
#endregion
#region 字段
#endregion
#region 信号
#endregion

#region 基类方法
func init(agent:SteeringBehaviorAgent):
	super.init(agent)
func enable():
	super()
	ray_cast_2d = RayCast2D.new()
	ray_cast_2d.target_position = Vector2(radius,0)
	ray_cast_2d.collision_mask = agent.get_obstacle_layer_mask()
	ray_cast_2d.enabled = false
	agent.add_child(ray_cast_2d)
func disable():
	super()
	if ray_cast_2d:
		ray_cast_2d.queue_free()
	ray_cast_2d = null
func update():
	super()
	targets = GameCampSystem.get_target(GameCampSystem.get_target_camps(agent.get_camp()),agent.get_pos(),true,-1,radius)
	ray_cast_2d.collision_mask = agent.get_obstacle_layer_mask()
func destroy():
	super()
#endregion
#region 公共方法
func get_closed_target(pos:Vector2,filter_func:Callable = Callable(),count:int = -1) -> Array[Node2D]:
	match target_type:
		GameEnum.TargetDetectorTargetType.Target:
			var targets_copy = targets.duplicate()
			if filter_func and filter_func.is_valid():
				targets_copy = targets_copy.filter(filter_func)
			targets_copy.sort_custom(func (a:Vector2,b:Vector2):return (a-pos).length() < (b-pos).length())
			return targets_copy.slice(0,count if count >= 0 else targets_copy.size())
		GameEnum.TargetDetectorTargetType.VisibleTarget:
			var targets_copy = targets.duplicate()
			targets_copy = targets_copy.filter(func(target):
				ray_cast_2d.target_position = target.global_position - agent.get_pos()
				ray_cast_2d.force_raycast_update()
				return not ray_cast_2d.is_colliding() and (filter_func.call(target) if filter_func and filter_func.is_valid() else true)
				)
			targets_copy.sort_custom(func (a:Vector2,b:Vector2):
				return (a-pos).length() < (b-pos).length()
			)
			return targets_copy.slice(0,count if count >= 0 else targets_copy.size())
		GameEnum.TargetDetectorTargetType.SameCampTarget:
			var targets_same_camp = GameCampSystem.get_target([agent.get_camp()],agent.get_pos(),true,-1,radius)
			if filter_func and filter_func.is_valid():
				targets_same_camp = targets_same_camp.filter(filter_func)
			targets_same_camp.sort_custom(func (a:Vector2,b:Vector2):return (a-pos).length() < (b-pos).length())
			return targets_same_camp.slice(0,count if count >= 0 else targets_same_camp.size())
		_:
			return []
#endregion
#region 私有方法
#endregion
#region 生命周期函数
#endregion
